from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import sys

import os
from google.appengine.ext.webapp import template

from models import *

class MainPage(webapp.RequestHandler):
	def get(self):
        	user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					user_id=i.admissionnumber
					if i.privilege=='admin':
						self.redirect("/admin")
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				team=db.GqlQuery("SELECT * FROM teamDetails")
				project=db.GqlQuery("SELECT * FROM projectDetails")
				notif=db.GqlQuery("SELECT * FROM notificationDetails")
				qns=db.GqlQuery("SELECT * FROM questionanswer")

				tid=[]
				ti=[]
				temp=[]
				fla=0
				for i in team:
					stri=i.teammember
					b=stri.split(',')
					for j in b:
						if (user_id==j):
							tid.append(i.projectids)
				t=[]
				for i in notif :
					if i.admissionnumber==user_id:	
						temp1=[i.notification,i.notificationid]
						t.append(temp1)

				ans=[]
				for i in qns :
					if i.admissionnumber==user_id:	
						temp1=[i.question,i.answer,i.questionid]
						ans.append(temp1)

				for i in project:
					for j in tid:
						temp=[]
						if i.projectid==j:
							temp=[i.projectname,i.projectid,i.teamid,i.category,i.abstract,i.confirmed]
							ti.append(temp)
				path = os.path.join(os.path.dirname(__file__),'tab.html')#use template
				self.response.out.write(template.render(path,{"items":ti,"noti":t,"email":user.email(),"ans":ans}))#using template		
			except:
				self.redirect("/")
				
		else:
		    self.redirect(users.create_login_url("/"))

	def post(self):
		delid=self.request.get("delval")
		if delid:
			notif=db.GqlQuery("SELECT * FROM notificationDetails WHERE notificationid='%s'"%(delid))
			for i in notif :
				i.delete()
		delid=self.request.get("delans")
		if delid:
			ans=db.GqlQuery("SELECT * FROM questionanswer WHERE questionid='%s'"%(delid))
			for i in ans :
				i.delete()
		self.redirect("/")
	
application=webapp.WSGIApplication([('/user',MainPage)],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
